package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"pet-guard/cache"
	"pet-guard/model"
	"strconv"
	"time"
)

func PetAdd(c *gin.Context) {
	name := c.PostForm("name")
	color := c.PostForm("color")
	data := model.Pet{
		Name:  name,
		Color: color,
	}
	model.DB.Create(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "2"))
	offset := (page - 1) * size
	var pet []model.Pet
	redis_key := "pet_list" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Offset(offset).Limit(size).Find(&pet)
		jsonData, _ := json.Marshal(pet)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &pet)
	}
	var total int64
	model.DB.Model(&model.Pet{}).Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "分页列表成功",
		"data":  pet,
		"total": total,
	})
	return
}
